from typing import Tuple
from src.core import log
from src.core import Enums
from src.db import dbm, dbs


def search_id_by_username(username: str) -> Tuple[Enums.SearchResult, str | None]:
    """根据用户名搜索用户ID, 搜索中途带日志输出！"""
    return search_user_by_username(username)


def search_user_by_username(username: str) -> Tuple[Enums.SearchResult, object]:
    """根据用户名搜索用户对象"""
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        try:
            db_result = (
                db_session.query(dbs.sys_default.User)
                .filter(dbs.sys_default.User.username == username)
                .all()
            )
            if len(db_result) == 0:
                log.ERROR(f"用户名 {username} 不存在。")
                return Enums.SearchResult.NOT_FOUND, None
            elif len(db_result) > 1:
                log.ERROR(f"用户名 {username} 存在多个用户，请检查数据库。")
                return Enums.SearchResult.MULTIPLE_FOUND, None
            else:
                user = db_result[0]
                return Enums.SearchResult.SUCCESS, user
        except Exception as e:
            log.ERROR(f"查询用户 {username} ID 失败: {str(e)}")
            raise RuntimeError(f"查询用户 {username} ID 失败: {str(e)}") from e
